<template>
  <div ref="mapChart" style="width: 100%; height: 100%;"></div>
</template>

<script>
import * as echarts from 'echarts';
import chinaMapData from '../data/china.json';
import { sseManager } from '@/api/tool/sse-manager.js';
import { throttle } from 'lodash-es';

// 颜色映射配置（更自然的颜色过渡）
const COLOR_RANGE = ['#FBF9FA', '#507AAF']; // 热力图风格蓝灰色调

export default {
  name: "GlobalHousingMap",
  data() {
    return {
      chart: null,
      unsubscribe: null,
      baseData: chinaMapData.features.map(feature => ({
        name: feature.properties.name,
        value: 0
      })),
      debug: true, // 调试开关，设为 false 可关闭日志
      totalSales: 0 // 新增：用于存储全国总销量
    };
  },
  mounted() {
    if (this.debug) console.log('[MapChart] 开始初始化地图组件');
    this.initChart();
    this.subscribeData();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    if (this.debug) console.log('[MapChart] 组件销毁前清理资源');
    this.cleanup();
  },
  methods: {
    /** 初始化地图 */
    initChart() {
      if (this.debug) console.log('[MapChart] 注册中国地图数据');
      echarts.registerMap('china', chinaMapData);

      const container = this.$refs.mapChart;
      if (!container) {
        console.error('[MapChart] 地图容器未找到');
        return;
      }

      if (this.debug) console.log('[MapChart] 初始化图表实例');
      this.chart = echarts.init(container);

      if (this.debug) console.log('[MapChart] 设置初始地图配置');
      this.chart.setOption({
        title: {
          text: '房屋全球销售分布（实时）',
          left: 'center',
          textStyle: {
            color: '#2c3e50',
            fontSize: 18
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            const value = params.value || 0;
            const percent = this.totalSales > 0 ? ((value / this.totalSales) * 100).toFixed(1) : 0;
            return `
              <div style="min-width:120px">
                <b>${params.name}</b>
                <div>销量：${value}套</div>
                <div>占比：${percent}%</div>
              </div>
            `;
          }
        },
        visualMap: {
          min: 0,
          max: 100, // 初始最大值（会被动态覆盖）
          inRange: {
            color: COLOR_RANGE
          },
          text: ['高销量', '低销量'],
          calculable: true, // 支持拖动滑块调整显示范围
          left: 20,
          bottom: 20,
          textStyle: {
            color: '#666'
          }
        },
        series: [{
          name: '房屋分布',
          type: 'map',
          map: 'china',
          roam: true,
          zoom: 1.2,
          label: {
            show: true,
            fontSize: 10,
            color: '#333'
          },
          itemStyle: {
            borderColor: '#fff',
            borderWidth: 1
          },
          emphasis: {
            label: {
              show: true,
              color: '#b22'
            },
            itemStyle: {
              areaColor: '#a6d8ff'
            }
          },
          data: this.baseData
        }]
      });
    },

    /** 订阅数据更新 */
    subscribeData() {
      if (this.debug) console.log('[MapChart] 订阅 SSE 数据流: house_distribution');

      // 添加500ms节流控制
      const updateHandler = throttle(data => {
        if (this.debug) console.log('[MapChart] 收到新数据:', data);
        this.updateMap(data);
      }, 500);

      this.unsubscribe = sseManager.subscribe('house_distribution', updateHandler);
    },

    /** 更新地图数据 */
    updateMap(payload) {
      if (this.debug) console.log('[MapChart] 开始更新地图数据:', payload);

      let rawData = [];

      // 判断是否是数组格式
      if (Array.isArray(payload?.data)) {
        rawData = payload.data;
      } 
      // 判断是否是对象格式（如：{ "北京": 45, "上海": 32 }）
      else if (typeof payload === 'object' && payload !== null) {
        rawData = Object.keys(payload).map(region => ({
          region,
          count: payload[region]
        }));
      } else {
        console.warn('[MapChart] 接收的数据无效或为空');
        return;
      }

      if (this.debug) console.log('[MapChart] 转换后的原始数据:', rawData);

      // 深拷贝基础数据防止污染
      const newData = JSON.parse(JSON.stringify(this.baseData));

      // 合并实时数据
      rawData.forEach(item => {
        const index = newData.findIndex(d => d.name === item.region);
        if (index !== -1) {
          if (this.debug) console.log(`[MapChart] 更新区域 [${item.region}] 的值为 ${item.count}`);
          newData[index].value = item.count;
        } else {
          if (this.debug) console.warn(`[MapChart] 未知区域: ${item.region}`);
        }
      });

      // 计算全国总销量
      const totalSales = newData.reduce((sum, item) => sum + (item.value || 0), 0);
      this.totalSales = totalSales;

      if (this.debug) console.log(`[MapChart] 全国总销量: ${totalSales}`);

      // 动态调整最大值
      const currentMax = Math.max(...newData.map(d => d.value), 1);
      if (this.debug) console.log(`[MapChart] 新最大值: ${currentMax}`);

      this.chart.setOption({
        visualMap: {
          max: currentMax
        },
        series: [{
          data: newData
        }]
      });

      if (this.debug) console.log('[MapChart] 地图数据更新完成');
    },

    /** 窗口缩放处理 */
    handleResize() {
      if (this.debug) console.log('[MapChart] 窗口大小改变，重新绘制地图');
      this.chart?.resize();
    },

    /** 资源清理 */
    cleanup() {
      if (this.debug) console.log('[MapChart] 清理资源');
      if (typeof this.unsubscribe === 'function') {
        if (this.debug) console.log('[MapChart] 取消 SSE 订阅');
        this.unsubscribe();
      }
      if (this.chart) {
        if (this.debug) console.log('[MapChart] 销毁 ECharts 实例');
        this.chart.dispose();
        this.chart = null;
      }
      window.removeEventListener('resize', this.handleResize);
    }
  }
};
</script>

<style scoped>
/* 添加加载动画 */
.map-chart-container {
  position: relative;
  background: #f8f9fa;
  border-radius: 8px;
  overflow: hidden;
}

.map-chart-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(
    to bottom right,
    rgba(255,255,255,0.8),
    rgba(255,255,255,0)
  );
  pointer-events: none;
}
</style>